export function formatDate(date, fmt) {
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  const o = {
    'M+': date.getMonth() + 1,
    'd+': date.getDate(),
    'h+': date.getHours(),
    'm+': date.getMinutes(),
    's+': date.getSeconds()
  }
  for (const k in o) {
    if (new RegExp(`(${k})`).test(fmt)) {
      const str = o[k] + ''
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
    }
  }
  return fmt
}
function padLeftZero(str) {
  return ('00' + str).substr(str.length)
}
export function timeTranslate(date) {
  if (!date) return date
  var newDate = new Date(date)
  var Month = newDate.getMonth() + 1
  var getM = Month < 10 ? '0' + Month : Month
  var _date = newDate.getDate() // 日
  var getD = _date < 10 ? '0' + _date : _date
  var time = newDate.getFullYear() + '-' + getM + '-' + getD
  return time
}

export function timeTranslateHMS(date, HMS, format = '-') {
  if (!date) {
    return
  }
  var newDate = new Date(date)
  var Month = newDate.getMonth() + 1
  var getM = Month < 10 ? '0' + Month : Month
  var _date = newDate.getDate() // 日
  var getD = _date < 10 ? '0' + _date : _date

  var hours = newDate.getHours() // 时
  var getHours = hours < 10 ? '0' + hours : hours
  var minutes = newDate.getMinutes() // 时
  var getMinutes = minutes < 10 ? '0' + minutes : minutes
  var seconds = newDate.getSeconds() // 时
  var getSeconds = seconds < 10 ? '0' + seconds : seconds

  var time = null
  if (HMS) {
    time = newDate.getFullYear() + '-' + getM + '-' + getD + ' ' + getHours + ':' + getMinutes + ':' + getSeconds
  } else {
    time = newDate.getFullYear() + format + getM + format + getD
  }

  return time === 'NaN-NaN-NaN' ? date : time
}

// 回到顶部
export function topY() {
  setTimeout(function() {
    window.scrollTo(0, 0)
  })
}

// 请求结果处理
export function res(response, callback) {
  var res = {
    resEntity: response.data,
    status: response.status
  }
  if (res.status === 200) {
    if (res.resEntity.code === '0000') {
      callback()
    } else {
      this.$Message.error(res.resEntity.msg)
    }
  } else {
    this.$Message.error(res.status)
  }
}
